import { refreshToken } from '@/api/user'

class TokenManager {
    constructor() {
        this.refreshInterval = 1000 * 60 * 30 // 30分钟刷新一次
        this.timeoutId = null
        this.lastRefreshTime = null
        this.isChecking = false // 添加检查状态标志
        this.initStorageListener()
    }

    // 添加 localStorage 监听器
    initStorageListener() {
        window.addEventListener('storage', (e) => {
            if (e.key === 'token' && e.newValue) {
                console.log('[TokenManager] 检测到token更新:', e.newValue)
                // 不在这里自动启动定时器
            }
        })

        // 同一页面内的 localStorage 变化监听
        const originalSetItem = localStorage.setItem
        localStorage.setItem = function(key, value) {
            const event = new Event('localStorageChange')
            event.key = key
            event.newValue = value
            window.dispatchEvent(event)
            originalSetItem.apply(this, arguments)
        }

        window.addEventListener('localStorageChange', (e) => {
            if (e.key === 'token' && e.newValue) {
                console.log('[TokenManager] 当前页面token已更新:', e.newValue)
                // 不在这里自动启动定时器
            }
        })
    }

    startRefreshTimer() {
        // 添加小延迟确保 localStorage 操作完成
        setTimeout(() => {
            this.stopRefreshTimer() // 确保不会重复启动定时器
            
            const token = localStorage.getItem('token')
            // console.log('[TokenManager] 准备启动定时器，当前token:', token)
            
            if (!token) {
                console.log('[TokenManager] token不存在，不启动定时器')
                return
            }

            // console.log('[TokenManager] 启动定时刷新器，间隔:', this.refreshInterval / 1000, '秒')
            
            this.timeoutId = setInterval(async () => {
                const currentToken = localStorage.getItem('token')
                if (currentToken) {
                    try {
                        // console.log('[TokenManager] 执行定时token刷新...')
                        const response = await refreshToken()
                        const newToken = response.data.data
                        // console.log('[TokenManager] 新token:', newToken)
                        localStorage.setItem('token', newToken)
                        
                        const now = new Date()
                        this.lastRefreshTime = now
                        // console.log('[TokenManager] Token刷新成功 - 时间:', now.toLocaleString())
                    } catch (error) {
                        // console.error('[TokenManager] Token自动刷新失败:', error)
                        this.stopRefreshTimer()
                        localStorage.removeItem('token')
                        localStorage.removeItem('userInfo')
                    }
                } else {
                    // console.log('[TokenManager] token已失效，停止定时刷新')
                    this.stopRefreshTimer()
                }
            }, this.refreshInterval)
        }, 100)
    }

    stopRefreshTimer() {
        if (this.timeoutId) {
            console.log('[TokenManager] 停止token定时刷新器')
            clearInterval(this.timeoutId)
            this.timeoutId = null
        }
    }

    async checkAndRefreshToken() {
        // 防止重复检查
        if (this.isChecking) {
            console.log('[TokenManager] 已有检查正在进行中，跳过本次检查')
            return false
        }

        const token = localStorage.getItem('token')
        if (!token) {
            console.log('[TokenManager] 初始检查：未找到token')
            return false
        }

        try {
            this.isChecking = true
            console.log('[TokenManager] 初始检查：尝试刷新token...')
            const response = await refreshToken()
            
            // 添加数据校验和详细日志
            console.log('[TokenManager] Token刷新完整响应:', response)
            
            if (!response.data?.data) {
                console.error('[TokenManager] Token响应格式错误:', response)
                throw new Error('Token响应格式错误')
            }
            
            // 修改这里：使用正确的数据格式 response.data.data
            const newToken = response.data.data
            
            // 添加token存储前的验证
            if (!newToken) {
                throw new Error('获取到的新token为空')
            }
            
            localStorage.setItem('token', newToken)
            console.log('[TokenManager] 新token已存储:', newToken)
            
            const now = new Date()
            this.lastRefreshTime = now
            console.log('[TokenManager] 初始token刷新成功 - 时间:', now.toLocaleString())
            
            this.startRefreshTimer()
            return true
        } catch (error) {
            console.error('[TokenManager] 初始token刷新失败:', error)
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            return false
        } finally {
            this.isChecking = false
        }
    }

    getLastRefreshTime() {
        return this.lastRefreshTime ? this.lastRefreshTime.toLocaleString() : '未刷新'
    }
}

export default new TokenManager()